import Cookies from 'js-cookie'
import vueRouter from '@/router'
import { adminUrl } from '@/config'

export const TOKEN_KEY = 'token'
export const setToken = token => {
    Cookies.set(TOKEN_KEY, token, { expires: 1 })
}
export const getToken = () => {
    const token = Cookies.get(TOKEN_KEY)
    const route = vueRouter?.currentRoute?.value
    if (token) return token
    return route?.query?.token || false
}

/** 获取 url 参数
 * @param {String} url
 * @param {String} value 要获取url的参数名
 * @returns {String} url参数值
 */
export const getUrlParams = (url, urlKey) => {
    const urlParams = {}
    url?.split('?')?.[1]?.split('&')?.forEach(item => {
        const key = item?.split('=')?.[0]
        const value = item?.split('=')?.[1]
        if (key && value) {
            urlParams[key] = value
        }
    })
    if (urlKey) {
        return urlParams[urlKey]
    }
    return urlParams
}

// 请求参数转换为 formData 格式
export const transformFormData = data => {
    if (Object.prototype.toString.call(data) !== '[object Object]') return data
    const formData = new FormData()
    Object.keys(data).forEach(key => formData.append(key, data[key]))
    return formData
}

// 打开后台
export const openAdmin = ({ path = 'home', appId }) => {
    const route = vueRouter?.currentRoute?.value
    appId ??= route?.params?.appId || ''
    window.open(`${adminUrl}${path}?appId=${appId}`, '_blank')
}